import { Body, Controller, Get, Post, Query, UseGuards } from '@nestjs/common';
import { DepartService } from './depart.service';
import { AuthGuard } from '@nestjs/passport';
import { Between, FindOptionsWhere, In } from 'typeorm';
import { Depart } from './depart.entity';
import { CurrentUser } from 'src/user/user.decorator';
import { UserSys } from 'src/user/userSys.entity';
import * as moment from 'moment';
import { ApiTags } from '@nestjs/swagger';
import { UserService } from 'src/user/user.service';

@Controller('api/depart')
@UseGuards(AuthGuard("jwt"))
@ApiTags("离职")
export class DepartController {
    constructor(
        private readonly departService: DepartService,
        private readonly userService: UserService
    ) { }

    @Post("add")
    async add(
        @Body() { users, time, reason, comment }
    ) {
        const list = await this.userService.userSys.find({
            where: { id: In(users) },
            relations: ["system"]
        })
        for (const user of list) {
            await this.departService.create(user, time, reason, comment);
        }
    }

    @Post("del")
    del(
        @Body() { ids }
    ) {
        return this.departService.depart.delete({ id: In(ids) })
    }


    @Get("get")
    async get(
        @Query("limit") limit: number,
        @Query("page") page: number,
        @Query("user") user: number,
        @Query("start") start: string,
        @Query("end") end: string,
        @CurrentUser() currentUser: UserSys
    ) {
        if (!limit) limit = 10;
        if (!page) page = 1;
        const where: FindOptionsWhere<Depart> = {
            system: {
                id: currentUser.system.id
            }
        }
        if (!!user) where.user = { id: user }
        if (!!start && !!end) where.time = Between(moment(start).toDate(), moment(end).toDate());
        const [data, count] = await this.departService.depart.findAndCount({
            where,
            relations: ["system", "user"],
            take: limit,
            skip: (page - 1) * limit,
            order: { id: "desc" }
        })
        return { data, count }
    }
}
